package cc.csln.so.cdelayqueue;

import cc.csln.so.cdelayqueue.jvm.JvmDelayQueue;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * Spring Boot 自动装配入口，提供延迟队列相关 Bean。
 * 作用：导入 {@link CDelayQueueConfig}，注册 `ThreadPoolTaskExecutor` 与 `IDelayQueue(JVM)`。
 * 条件：线程池 Bean 缺失时提供默认；当 `c-delay-queue.type=jvm` 时注册 JVM 实现。
 *
 * @author Cusalt
 * @since 2025/10/17 14:27
 **/
@Configuration
@Import(CDelayQueueConfig.class)
@RequiredArgsConstructor
public class CDelayQueueConfiguration {

    /**
     * 组件配置绑定（c-delay-queue.*）。
     */
    private final CDelayQueueConfig config;

    /**
     * 注册默认的回调执行线程池。
     * 条件：当容器中不存在 `ThreadPoolTaskExecutor` 时生效。
     * 配置来源：
     * - `c-delay-queue.thread-pool.core-pool-size`
     * - `c-delay-queue.thread-pool.max-pool-size`
     * - `c-delay-queue.thread-pool.queue-capacity`
     * - `c-delay-queue.thread-pool.keep-alive-seconds`
     * - `c-delay-queue.thread-pool.thread-name-prefix`
     */
    @Bean
    @ConditionalOnMissingBean(ThreadPoolTaskExecutor.class)
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(config.getThreadPool().getCorePoolSize());
        executor.setMaxPoolSize(config.getThreadPool().getMaxPoolSize());
        executor.setQueueCapacity(config.getThreadPool().getQueueCapacity());
        executor.setKeepAliveSeconds(config.getThreadPool().getKeepAliveSeconds());
        executor.setThreadNamePrefix(config.getThreadPool().getThreadNamePrefix());
        executor.initialize();
        return executor;
    }

    /**
     * JVM 实现的延迟队列自动装配。
     * 条件：`c-delay-queue.type=jvm`。
     */
    @Configuration
    @RequiredArgsConstructor
    @ConditionalOnProperty(prefix = "c-delay-queue", name = "type", havingValue = "jvm")
    public static class JvmDelayQueueConfiguration {

        /**
         * 注册 `IDelayQueue` 的 JVM 实现。
         * 参数：
         * - `config`：读取 `c-delay-queue.jvm.*` 配置（默认延迟等）
         * - `taskExecutor`：用于异步执行任务回调
         */
        @Bean
        public IDelayQueue delayQueue(CDelayQueueConfig config, ThreadPoolTaskExecutor taskExecutor) {
            return new JvmDelayQueue(config.getJvm(), taskExecutor);
        }

    }
}
